﻿using System;
using System.Configuration;
using System.Web;

namespace DAL
{
    public static class ConnectionStringLoader
    {
        private const string SEO_GENIECONNECTIONSTRING = "dbConnectionString";
        private static string _connectionString = string.Empty;
        private static string _connectionStringName = string.Empty;

        public static string ConnectionName
        {
            get
            {
                if (!string.IsNullOrEmpty(_connectionStringName))
                    return _connectionStringName;

                LoadConnection();

                return _connectionStringName;
            }
        }

        public static string GetConnectionStr
        {
            get
            {
                if (!string.IsNullOrEmpty(_connectionString))
                    return _connectionString;

                LoadConnection();

                return _connectionString;
            }
        }

        public static string LoadConnection()
        {
            _connectionStringName = SEO_GENIECONNECTIONSTRING;
            if (HttpContext.Current != null)
            {
                var conections = HttpContext.Current.GetSection("connectionStrings") as ConnectionStringsSection;
                if (conections != null)
                    if (conections.ConnectionStrings[_connectionStringName] != null)
                        _connectionString = conections.ConnectionStrings[_connectionStringName].ConnectionString;
            }
            else
            {
                if (ConfigurationManager.ConnectionStrings.Count > 0)
                    if (ConfigurationManager.ConnectionStrings[_connectionStringName] != null)
                        _connectionString = ConfigurationManager.ConnectionStrings[_connectionStringName].ConnectionString;
            }

            if (string.IsNullOrEmpty(_connectionString))
                throw new ArgumentException(
                    string.Format(@"Configuration Not Set , Please Set: {0} in the connectionString Section", _connectionStringName));

            return _connectionString;
        }
    }
}